package cn.willbj.brief.hootl.socket.demo;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

/**
 * 查看端口是否已使用
 *
 */
public class Demo01 {
	public static void main(String[] args) {
		Demo01.test03();
		
		Demo01.test01();
		Demo01.test02();
	}

	public static void test01() {
		try {
			InetAddress localHost = InetAddress.getLocalHost();
			System.out.println(localHost.getHostAddress());
			System.out.println(localHost.getHostName());
			System.out.println(InetAddress.getLoopbackAddress().getHostName());
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
	}

	public static void test02() {
		for (int i = 3300; i < 3310; i++) {
			try {
				Socket socket = new Socket("localhost", i);
				System.out.println("被监听: " + i);
			} catch (IOException e) {
				System.err.println("没有被监听" + i);
			}
		}
	}

	public static void test03() {
		int size;
		URL url;
		URLConnection conn = null;
		try {
			url = new URL("http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png");
			conn = url.openConnection();
			size = conn.getContentLength();
			if (size < 0)
				System.out.println("无法获取文件大小。");
			else
				System.out.println("文件大小为：" + size + " bytes");
		} catch (Throwable e) {
			e.printStackTrace();
		}finally {
			try {
				conn.getInputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
